package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.server.interceptor.UserHolderThreadLocal;
import com.tanhua.utils.Constants;
import com.tanhua.utils.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/11/27 20:13
 */


@Service
public class UserService {

    public   final static String check = "CODE_CHECK_";

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    // 服务提供者
    @DubboReference
    private UserApi userApi;

    @Autowired
    private UserFreezeService userFreezeService;

    /**
     * 发送验证码
     * @param phone
     */
    public void sendCode(String phone) {

        //校验用户状态--------------------------
        User user = userApi.findByPhone(phone);
        if (user != null) {
            userFreezeService.checkUserStatus(1,user.getId());
        }

        // 1. 获取验证码
//        String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";

        // 2. 发送短信
//        smsTemplate.sendSms(phone, code);

        // 3. 将验证码存入到redis、
        redisTemplate.opsForValue().set( check + phone, code, Duration.ofMinutes(5));
    }

    /**
     * 验证码校验
     * @param phone
     * @param code
     * @return
     */
    public Map loginVerification(String phone, String code) {
        // 1. 从redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(check + phone);
        // 2. 判断输入的验证码是否正确
        if(code.isEmpty() || !code.equals(redisCode)){
            throw new RuntimeException("验证吗失效了");
        }
        // 3. 删除redis的验证码
        redisTemplate.delete(check + phone);
        // 判断用户是否登录
        User user = userApi.findByPhone(phone);
        // 是否是新用户
        boolean isNew = false;
        if(user == null){
            // 新用户就添加到数据库
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            userApi.add(user);
            User user1 = userApi.findByPhone(phone);
            user.setId(user1.getId());
            isNew = true;

            // 注册环信用户
            String hxUserName = Constants.HX_USER_PREFIX + user.getId();
            String hxPassword = Constants.INIT_PASSWORD;
            boolean flage = huanXinTemplate.creatUser(hxUserName, hxPassword);
            if (flage) {
                user.setHxUser(hxUserName);
                user.setHxPassword(hxPassword);
                userApi.update(user);
            }
        }

        // 登录成功生成token

        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("phone", phone);
        String token = JwtUtils.getToken(map);

        // 封装数据返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);
        return result;

    }
}
